#include <map>
#include <vector>

#include "event.h"
#include "eventdispatch.h"
#include "reactor.h"

namespace reactor{

struct ReactorPrivate{
public:
    ReactorPrivate(){
#ifdef USE_EPOLL

#elif USE_SELECT

#elif USE_KQUEUE

#else
        m_event_dispatch = new EpollEventDispatchImp(this);
#endif
    }
    ~ReactorPrivate(){}

    int registerEvent(Event * ev,int t){
        /// 等待释放事件队列，当关闭后的链接会被加入到这个队列，并在下一次注册的某一事件的时候进行释放内存
        /// 这个事件是在服务器接受
        while(m_wait_free_events.size() > 0){
            Event * temp = m_wait_free_events.back();
            m_wait_free_events.pop_back();
            delete temp;
        }

        Handle handle = ev->getHandle();
        std::map<Handle,Event *>::const_iterator it = m_h_events.find(handle);
        /// 如果没有在映射中没有找到handle对应的ev，那么说明没有，那么重新插入新事件
        /// 如果找到了，那么就设置为更新事件，说明并没有超时，此时如果修改了超时时间，那么应该更新使用新的时间
        if(it == m_h_events.end()){
            /// 对定时时间合法性检查，失败则添加默认最大时间，默认为120天，需要考虑数值存储的合法性
            if(t <= 0 || t > TIMEOUT_MAX_VALUE){
                ev->setTimeout(TIMEOUT_MAX_VALUE);//set MAX timeout
            }else{
                ev->setTimeout(t);
            }
            m_h_events[handle] = ev;
            m_event_dispatch->addHeap(ev);
            m_event_dispatch->add(ev);
        }else {
            if(ev == m_h_events[handle]){
                if(t <= 0 || t > TIMEOUT_MAX_VALUE){
                    ev->setTimeout(TIMEOUT_MAX_VALUE);
                }else {
                    ev->setTimeout(t);
                }
                ev->setUpdateEvent(true);
            }else{
                print_msg("update ev error");
            }
        }
        return 0;
    }
    int removeEvent(Event * ev){
        if(m_h_events.find(ev->getHandle()) != m_h_events.end()){
            m_wait_free_events.push_back(ev);
            m_h_events.erase(ev->getHandle());
            return m_event_dispatch->remove(ev);
        }else{
            print_msg("already remove");
        }
        return 0;
    }

    int execEvents(){
        return m_event_dispatch->dispatch(&m_h_events);
    }

private:
    /// reactor维护handle和event的映射、待释放的队列
    friend class Reactor;
    EventDispatch * m_event_dispatch;//对应的桥接模式，拥有相似的接口
    std::map<Handle,Event *> m_h_events;
    std::vector<Event *> m_wait_free_events;

};

Reactor::Reactor():m_d(new ReactorPrivate()){}

Reactor::~Reactor(){
    delete m_d;
}

int Reactor::registerEvent(Event * ev, int time){
    return m_d->registerEvent(ev,time);
}

int Reactor::removeEvent(Event * ev){
    m_d->removeEvent(ev);
    return 0;
}

int Reactor::execEvents(){
    return m_d->execEvents();
}

}

